import java.util.ArrayList;
import java.util.List;

public class Solution1363 {
    public String largestMultipleOfThree(int[] digits) {
        int a=0,b=0;
        List<Integer> l1=new ArrayList<>();
        List<Integer> l2=new ArrayList<>();
        List<Integer> l3=new ArrayList<>();
        for (int digit : digits) {
            if (digit%3==1){
                a++;
                l2.add(digit);
            }else if (digit%3==2){
                b++;
                l3.add(digit);
            }else {
                l1.add(digit);
            }
        }
        l2.sort((x,y)->y-x);
        l3.sort((x,y)->y-x);
        int c=0,d=0;
        int k=Math.abs(a-b)/3;
        if (a>b){
            a=a-k*3;
            c+=k*3;
        }else {
            b=b-k*3;
            d+=k*3;
        }
        int m=Math.min(a,b);
        if (Math.abs(a-b)<=1) {
            c+=m;
            d+=m;
        }else {
            if (b>a){
                c+=m-1;
                d+=m+2;
            }else {
                d+=m-1;
                c+=m+2;
            }
        }
        if (c>=0 && d>=0){
            for (int i=0;i<c;i++){
                l1.add(l2.get(i));
            }
            for (int i=0;i<d;i++){
                l1.add(l3.get(i));
            }
        }
        l1.sort((x,y)->y-x);
        if (l1.size()==0){
            return "";
        }
        if (l1.get(0)==0){
            return "0";
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (Integer integer : l1) {
            stringBuilder.append(integer);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Solution1363().largestMultipleOfThree(new int[]{1,1,1,2}));
    }
}
